<!-- 退款订单 -->
<template>
  <div>
    <a-modal :width="1200" title="退款订单" :open="openForm" @cancel="onClose" :maskClosable="false" :destroyOnClose="true" :footer="false">
      <div>
        <a-form class="smart-query-form">
          <a-row class="smart-query-form-row">
            <a-col :span="7">
              <a-form-item label="退款订单号" class="smart-query-form-item">
                <a-select
                  style="width: 30%"
                  v-model:value="queryForm.orderField"
                  :options="ORDER_FIELD_REFUND"
                  :dropdown-match-select-width="false"
                  placeholder="请选择"
                  @change="onChangeOrderField"
                />
                <a-input style="width: 60%" v-model:value="queryForm[queryForm.orderField]" placeholder="退款订单号" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="退款状态" class="smart-query-form-item">
                <a-select v-model:value="queryForm.status" allowClear :options="REFUND_TYPE" placeholder="请选择退款状态" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="退款日期" class="smart-query-form-item">
                <a-range-picker class="w-full" v-model:value="queryForm.complaintTime" :valueFormat="'YYYY-MM-DD'" @change="changeComplaintTime" />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="getSettlementList">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                  重置
                </a-button>
              </a-form-item></a-col
            >
          </a-row>
        </a-form>
        <a-table :dataSource="tatleData" :columns="columns" bordered :pagination="false" size="small" />
      </div>
    </a-modal>
  </div>
</template>
<script setup>
  import { nextTick, reactive, ref, computed, watch } from 'vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { refundApi as refundApiMerchant } from '/@/api/business/b-merchant/refund/refund-api'
  import { refundApi as refundApiOperation } from '/@/api/business/b-operation/refund/refund-api'
  import dayjs from 'dayjs'
  import _ from 'lodash'
  import {
    ORDER_TYPE, //订单类型
    ORDER_FIELD_REFUND, //订单号对应字段
    REFUND_TYPE, //退款状态
    OPERATE_TYPE, // 操作类型
  } from '/@/constants/dict'
  import { selectDictLabel } from '/@/utils/common'
  import { message, Tag } from 'ant-design-vue'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    listApi: (data) => {
      if (USER_TYPE == '4') return refundApiMerchant.page(data)
      if (USER_TYPE == '1') return refundApiOperation.page(data)
    },
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emit = defineEmits(['update:open', 'ok', 'cancel'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  const queryFormState = {
    orderField: 'keyWord',
    keyWord: undefined, //全部
    orderId: undefined,
    oId: undefined, //支付订单号（支付宝/微信返回的订单号）
    tId: undefined, //渠道订单号（间连返回的订单编号）
    merchantId: undefined, //商户名称
    id: undefined, //退款订单号
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = ref({ ...queryFormState })

  // 获取结算列表
  const tatleData = ref([])
  async function getSettlementList(data) {
    tableLoading.value = true
    try {
      const payload = { ...queryForm.value }
      delete payload.tTime
      let queryResult = await apiSource.listApi(payload)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }
  async function show(rowData) {
    console.log(rowData)

    queryForm.value.id = rowData.complaintNo
    await getSettlementList()
    // nextTick(() => {
    //   formRef.value?.clearValidate()
    // })
  }

  function onClose() {
    tatleData.value = []
    // Object.assign(form, formDefault)
    emit('cancel', false)
    openForm.value = false
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.value.pageSize
    Object.assign(queryForm.value, queryFormState)
    queryForm.value.pageSize = pageSize
    queryData()
  }
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)
  // ------------------------ 表单 ------------------------

  /* 列表数据 */

  const columns = ref([
    {
      title: '退款订单号',
      dataIndex: 'refundOrder',
      width: 300,
      customRender: (column) => {
        let { id, oId, tId } = column.record
        let mText = id ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: '#2db7f5' }, '交易'), id]) : ''
        let oText = oId ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: 'orange' }, '支付'), oId]) : ''
        let tText = tId ? h('div', [h(Tag, { color: 'cyan' }, '渠道'), tId]) : ''

        return h('div', [mText, oText, tText])
      },
      ellipsis: true,
    },
    {
      title: '交易余额',
      dataIndex: 'orderBalance',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '手续费退还金额',
      dataIndex: 'fee',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '退款状态',
      dataIndex: 'fee',
      customRender: ({ text }) => {
        return selectDictLabel(REFUND_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '退款失败原因',
      dataIndex: 'failMsg',
      ellipsis: true,
    },
    {
      title: '退款时间',
      dataIndex: 'fTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      width: 180,
      ellipsis: true,
    },
  ])

  /* 列表数据 */

  defineExpose({
    show,
  })
  // 切换订单号选择
  watch(
    () => queryForm.value.orderField,
    (val, oldVal) => {
      if (val) {
        queryForm.value[oldVal] = undefined
      }
    },
  )
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
